package com.putable.cgw.game.yard;

import java.awt.Dimension;
import java.awt.Point;

import com.putable.cgw.game.member.Member;
/**
 * 
 * @author Todd
 *
 */
public abstract class AbstractYard implements Yard {
	private Member[][] yard;
	private Dimension dimension;
	private int size = 0; //Num members in the yard.

	public AbstractYard(Dimension size) {
		this.dimension = size;
		yard = new Member[size.width][size.height];
	}
	
	public Member get(Point pos) {
		return get(pos.x,pos.y);
	}
	
	public Member get(int x, int y) {
		return yard[x][y];
	}

	public boolean put(Member m) {
		if (m.getPosition().x > yard.length || m.getPosition().y > yard[0].length)
			throw new ArrayIndexOutOfBoundsException("Position of Member Out of Yard");
		// Returns false if a member is already in that position
		if (yard[m.getPosition().x][m.getPosition().y] != null)
			return false;
		yard[m.getPosition().x][m.getPosition().y] = m;
		m.setYard(this);
		size++;
		return true;
	}

	public void erase(Point p) {
		erase(p.x, p.y);
	}
	
	public void eraseAll(){
		for(Member list[] : yard){
			for(Member m : list){
				erase(m.getPosition());
			}
		}
	}
	
	public void erase(int x, int y) {
		if(yard[x][y] != null){
			size--;
			yard[x][y].setYard(null);
		}
		yard[x][y] = null;
	}
	

	public Dimension getDimension(){
		return dimension;
	}
	
	public int size(){
		return size;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String str = "AbstractYard [dimension=" + dimension + ", size=" + size + "]";
		if(size == 0) return str;
		for(Member list[] : yard){
			for(Member m : list){
				if(m != null) str = str + "At " + m.getPosition() + " is a " + m.getClass().getName();
			}
		}
		return str;
	}
}
